$(document).ready(function () {
    $("#outbound-order-no").focus();

    //入库单查询
    $("#entry-order-btn").on("click", function () {
        const value = $('#entry-code-info').val();
        if (!value) {
            return;
        }

        if (!$('#box-code').text() && !pattern.test(value)) {
            BootstrapDialog.show({
                size: BootstrapDialog.SIZE_NORMAL,
                message: "请先输入货箱编号",
                closable: false,
                onshown: function (dialogRef) {
                    setTimeout(function () {
                        dialogRef.close();
                        clearInput("entry-code-info");
                    }, 3000);
                },
                buttons: [{
                    label: '关闭',
                    action: function (dialogItself) {
                        dialogItself.close();
                        clearInput("entry-code-info");
                    }
                }, {
                    label: '确定',
                    cssClass: 'btn-primary',
                    action: function (dialog) {
                        dialog.close();
                        clearInput("entry-code-info");
                    }
                }]
            });
            return;
        }

        initByInput(value);
        selectByEntryCode(value);
    });

    //入库
    $('#entry-box').on("click", function () {
        const boxCode = $('#box-code').text();
        entryCheck(boxCode, false);
    });

    /**
     * 确定按钮执行方法，取货单查询
     */
    $(".confirm-btn").click(function () {
        const value = $('.input').val();
        if (!value) {
            return;
        }
        initByInput(value);
        if (!$('#delivery-order').val()) {
            BootstrapDialog.show({
                size: BootstrapDialog.SIZE_NORMAL,
                message: "取货单编号不存在",
                closable: false,
                onshown: function (dialogRef) {
                    setTimeout(function () {
                        dialogRef.close();
                    }, 3000);
                    clearInput("entry-order-no");
                },
                buttons: [{
                    label: '关闭',
                    action: function (dialogItself) {
                        dialogItself.close();
                        clearInput("entry-order-no");
                    }
                }, {
                    label: '确定',
                    cssClass: 'btn-primary',
                    action: function (dialog) {
                        dialog.close();
                        clearInput("entry-order-no");
                    }
                }]
            });
            return;
        }
        deliverCode();
        // purchaseEmptyDown();
    });

    isEntry();
});

//分拣称重
function sortWeightCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    console.log("分拣称重响应：" + JSON.stringify(data));
    if (!cancel) {
        console.log("采购称重回调处理：" + JSON.stringify(data));
        delResponseFromWcs(data, opt);
        const obj = data.data;
        $('#' + obj.warehousingEntryId).show();
        if (obj.code == 0) {
            //采购入库称重响应更新实际重量
            if (obj.warehousingEntryId) {
                // $('#' + obj.warehousingEntryId).hide();
                $('#entry-order-btn').removeClass("hidden");
                $('#entry-box').removeClass("hidden");
                //更新为已称重
                $('#sort-table').bootstrapTable('updateByUniqueId', {
                    id: obj.warehousingEntryId,
                    row: {
                        weightDone: true,
                        actWeight: obj.totalWeight
                    }
                });
                clearInput("entry-code-info");
            }
        } else {
            BootstrapDialog.alert(obj.msg);
        }
    }
}

//货箱离开库位
function leaveBufferPosCallBack(data, cancel, opt) {
    if (!data) {
        // purchaseEmptyDown();
        return;
    }
    console.log("入库离开缓存位响应：" + JSON.stringify(data));
    if (!cancel) {
        autoConfirm = false;
        delResponseFromWcs(data, opt);
        const obj = data.data;
        if (obj.code == 0) {
            $('#sort-table').bootstrapTable('destroy');
            initEntryTable(null);
            $("#entry-code-info").val("");
            $('#entry-code-info').focus();
            $('#box-code').text("");
            $('#temp-num').val("");
            $('#temp-name').text("");
            $('#temp-code').text("");

            //wcs响应成功，则延时一秒再下，缓解下频率
            setTimeout(function () {
                // deliverCode();
                isEntry();
                clearInput("entry-code-info");
                $('#temp-num').val(obj.actTemperatureCode);
                // purchaseEmptyDown();
            }, 1000);
        } else {
            BootstrapDialog.show({
                size: BootstrapDialog.SIZE_NORMAL,
                message: obj.msg,
                closable: false,
                onshown: function (dialogRef) {
                    setTimeout(function () {
                        dialogRef.close();
                        clearInput("entry-code-info");
                    }, 3000);
                },
                buttons: [{
                    label: '确定',
                    cssClass: 'btn-primary',
                    action: function (dialog) {
                        dialog.close();
                        clearInput("entry-code-info");
                    }
                }]
            });
            const entry = $('#sort-table').bootstrapTable('getData');
            if (entry && entry.length > 0) {
                for (let i = 0; i < entry.length; i++) {
                    $('#' + entry[i].id).show();
                    $('#' + entry[i].id + "-del").show();
                }
            }
        }
    }
}

let dialogInfo = null;
let autoConfirm = false;

//发送指令响应回调
function wcsToWmsResponseCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    if (cancel) {
        //todo 隐藏操作按钮等之类的
        $("#empty-btn").addClass("hidden");
    } else {
        const obj = data.data;
        delResponseFromWcs(data, opt);
        console.log("iiiiiiiiiiiiii" + JSON.stringify(obj));
        if (obj.code == 1) {
            $('#entry-box').removeClass("hidden");
            if (autoConfirm === false) {
                autoConfirm = true;
                const response = obj.data;
                console.log("采购入库称重响应：" + JSON.stringify(response));
                if (response && response.ErrorID === 107) {
                    if (dialogInfo) {
                        dialogInfo.close();
                    }
                    dialogInfo = BootstrapDialog.confirm({
                        title: '信息提示',
                        message: obj.msg + ",货箱内物品重量为：" + obj.totalWeight + "；是否强制入库？",
                        btnCancelLabel: '取消', // <-- Default value is 'Cancel',
                        btnOKLabel: '强制入库', // <-- Default value is 'OK',
                        callback: function (result) {
                            if (result) {
                                $("#box-weight-info").val(obj.totalWeight);
                                entryForce(obj);
                            } else {
                            }
                            autoConfirm = false;
                        }
                    });
                } else {
                    BootstrapDialog.alert(obj.msg);
                }
            }
        } else {

        }
    }
}

//入库到位回调
function storageDoneCallBack(obj, cancel, opt) {
    if (!cancel) {
        const obj = data.data;
        delResponseFromWcs(obj, opt);
        if (obj.code == 1) {
            BootstrapDialog.alert(obj.msg);
        } else {

        }
        /*$('#ware-box-code').val("");
        $('#box-code-info').val("");
        $('#entry-code').val("");
        $('#entry-code-info').removeAttr("disabled");
        $('#entry-order-btn').removeClass("hidden");
        $('#entry-box').removeClass("hidden");
        clearInput('entry-code-info');*/
    }
}

//回调处理
function weighRespCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    if (!cancel) {
        delResponseFromWcs(data, opt);
        const obj = data.data;
        if (obj.code == 0) {
            //采购入库称重响应更新实际重量
            /*if (obj.warehousingEntryId) {
                $('#' + obj.warehousingEntryId).hide();
                $('#entry-order-btn').removeClass("hidden");
                $('#entry-box').removeClass("hidden");
                //更新为已称重
                $('#sort-table').bootstrapTable('updateByUniqueId', {
                    id: obj.warehousingEntryId,
                    row: {
                        weightDone: true,
                        actWeight: obj.totalWeight
                    }
                });
                clearInput("entry-code-info");
            }*/
        } else {
            // $('#' + obj.warehousingEntryId).show();
            BootstrapDialog.alert(obj.msg);
        }
    }
}

//出库到缓存位
function inBufferPosCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    if (!cancel) {
        //todo 逻辑处理
        const obj = data.data;
        if (obj.code == 0) {
        } else {
            delResponseFromWcs(data, opt);
        }
    } else {
    }
}

//入库缓存位扫码响应
function pageEntryCallBack(data) {
    console.log("入库缓存位扫码响应：" + data);
    if (data) {
        const vc = JSON.parse(data);
        if (vc.code == 0) {
            const resultData = vc.data;
            if (autoConfirm === false) {
                $("#entry-code-info").val(resultData.BoxCode);
                $("#entry-order-btn").click();
            }
        } else {
            BootstrapDialog.alert(vc.msg);
        }
    }
}

/**
 * 采购入库空箱下架
 */
function purchaseEmptyDown() {
    const deliveryOrder = $('#delivery-order').val();
    if (!deliveryOrder) {
        return;
    }
    const ops = $("#form-param").serializeJSON();
    $.ajax({
        type: "POST",
        url: "/wcs/purchaseEmptyDown",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(ops),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $('#spu-box-code').text($('#goods-box-code').val());
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                }
            }
        }
    });
}

//强制入库
function entryForce(obj) {
    if (!$('#ware-box-code').text() && !$('#box-code').text()) {
        BootstrapDialog.alert("货箱编号为空");
        return;
    }
    /*if (!$('#entry-code').text()) {
        BootstrapDialog.alert("入库单为空");
        return;
    }*/
    const entry = $('#sort-table').bootstrapTable('getData');
    //采购入库不允许空箱入库，返回空箱出入库处理
    if (entry.length < 1) {
        BootstrapDialog.alert("货箱明细不存在");
        return;
    }

    $("#box-weight-info").val(obj.totalWeight);
    console.log("weight:" + JSON.stringify(obj));
    $("#entry-box").addClass('hidden');
    //材料箱
    const ops = $("#form-param").serializeJSON();

    console.log("sps:" + JSON.stringify(ops));
    //转换为详情
    for (let i = 0; i < entry.length; i++) {
        delete entry[i]['id'];
    }
    ops['list'] = entry;
    $.ajax({
        type: "POST",
        url: "/wcs/entryForce",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(ops),
        dataType: "json",
        success: function (data) {
            console.log(data);
            if (data.code == 0) {

            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $('#spu-box-code').text($('#goods-box-code').val());
            $("#entry-box").removeClass("hidden");
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                }
            }
        }
    });
}

//校验取货单是否成功
function isEntry() {

    const opt = $("#form-param").serializeJSON();
    $.ajax({
        type: "POST",
        url: "/wcs/entry/selectEntryCodeByClient",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.code == 0) {
                // $('#entry-code-info').removeAttr("disabled");
                $('#entry-order-btn').removeClass("hidden");
                $('#entry-box').removeClass("hidden");
                $('#entry-code').val("");
                $('#ware-box-code').val("");
                $('#box-code-info').val("");

                $('#outbound-input').addClass('hidden');
                $('#entry-order-btn').removeClass('hidden');
                $('#delivery-order').val(data.data);
                $('.entry-order-cls').removeClass('hidden');
                $('#outbound-nav').removeClass('hidden');
                deliverCode();
                $('#entry-code-info').focus();
            } else {
                if (data.code == 1) {
                    $('#outbound-nav').addClass("hidden");
                    $('#outbound-input').removeClass('hidden');
                    $('#delivery-order').val("");
                    $('.entry-order-cls').addClass('hidden');
                    $('#box-code-info').val("");
                    $('#entry-order-no').val("");
                    $('#entry-order-no').focus();
                    // commitToPlatformInfo();
                    // window.history.back();
                } else {
                    BootstrapDialog.confirm({
                        title: "信息提示",
                        message: "当前有采购入库单正在操作，请稍后！",
                        btnCancelLabel: '返回',
                        btnOKLabel: '采购入库',
                        callback: function (result) {
                            // 点击确定按钮时，result为true
                            if (result) {
                                parent.location.reload();
                            } else {
                                parent.location.reload();
                            }
                        }
                    });
                }
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            BootstrapDialog.alert({
                title: "信息提示！",
                closable: false,
                message: XMLHttpRequest.responseJSON.msg
            });
        }
    });
}

//取货单查询采购单详情
function deliverCode() {
    const stockInCode = $("#delivery-order").val();
    if (!stockInCode) {
        clearInput("entry-order-no");
        return;
    }
    let ops = $("#form-param").serializeJSON();
    $.ajax({
        type: "POST",
        url: "/wcs/order/deliver/entryByDeliverCode",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(ops),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
                if (data.data.length != 0) {
                    const purchaseOrderCode = data.data.purchaseOrderCode;
                    //根据取货单获取采购详情
                    purchaseDetail(data.data);
                    initEntryTable(data.data);
                    $('#purchase-order-code').val(purchaseOrderCode);
                    console.log("deliverCode");
                    $('#entry-code-info').focus();
                } else {
                    parent.location.reload();
                    /*$('#outbound-nav').addClass("hidden");
                    $('#outbound-input').removeClass('hidden');
                    $('#delivery-order').val("");
                    $('.entry-order-cls').addClass('hidden');
                    $('#box-code-info').val("");
                    $('#entry-order-no').focus();*/
                    // commitToPlatformInfo();
                    /* BootstrapDialog.show({
                         size: BootstrapDialog.SIZE_NORMAL,
                         message: "信息不存在，请重新输入",
                         closable: false,
                         buttons: [{
                             label: '确定',
                             cssClass: 'btn-primary',
                             action: function (dialog) {
                                 dialog.close();
                                 clearInput("entry-order-no");
                             }
                         }]
                     });*/
                }
            } else {
                BootstrapDialog.show({
                    size: BootstrapDialog.SIZE_NORMAL,
                    message: data.msg,
                    closable: false,
                    onshown: function (dialogRef) {
                        setTimeout(function () {
                            dialogRef.close();
                            clearInput("entry-order-no");
                        }, 3000);
                    },
                    buttons: [{
                        label: '确定',
                        cssClass: 'btn-primary',
                        action: function (dialog) {
                            dialog.close();
                            clearInput("entry-order-no");
                        }
                    }]
                });
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            BootstrapDialog.alert({
                title: "信息提示！",
                closable: false,
                message: XMLHttpRequest.responseJSON.msg
            });
        }
    });
}

/**
 * 入库单提交到平台
 */
function commitToPlatformInfo() {
    let ops = $("#form-param").serializeJSON();
    $.ajax({
        type: "POST",
        url: "/wcs/entry/commitToPlatformInfo",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(ops),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {

            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            BootstrapDialog.alert({
                title: "信息提示！",
                closable: false,
                message: XMLHttpRequest.responseJSON.msg
            });
        }
    });
}

function purchaseDetail(data) {
    $('.outbound-order-cls').addClass("hidden");
    $('.entry-order-cls').removeClass("hidden");
    $('#outbound-nav').removeClass('hidden');
    clearInput('entry-code-info');
    for (let i = 0; i < data.length; i++) {
        data[i].quantityOfBox = data[i].quantityOfBox - data[i].inQuantityOfBox;
    }
    $('#purchase-detail-table').bootstrapTable({
        data: data,
        method: 'post',
        pagination: false,//不分页
        sortable: false, //不排序
        sidePagination: "server",
        uniqueId: 'id',
        striped: true,
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            let temp = $("#search-condition").serializeJSON();
            /*temp["rows"] = params.limit;                        //页面大小
            temp["page"] = (params.offset / params.limit) + 1;  //页码
            temp["sort"] = params.sort;                         //排序列名
            temp["sortOrder"] = params.order;      */             //排位命令（desc，asc）
            temp["purchaseOrderCode"] = purchaseOrderCode;
            return temp;
        },
        onLoadSuccess: function (data) {
            console.log("purchaseDetail");
            $('#entry-code-info').focus();
        },
        columns: [{
            field: 'spuName',
            title: '名称'
        }, {
            field: 'temperatureZone',
            title: '温区'
        }, {
            field: 'purchaseQuantity',
            title: '数量'
        }, {
            field: 'unit',
            title: '单位'
        }, {
            field: 'purchaseWeight',
            title: '重量'
        }, {
            field: 'spuId',
            title: '原料',
            visible: false
        }, {
            field: 'boxCode',
            title: '货箱'
        }, {
            field: 'opt',
            title: '操作',
            align: 'center',
            valign: 'middle',
            formatter: loss,
        }]
    });
}

function loss(value, row, index, field) {
    let result = '';
    //row.purchaseOrderCode, boxCode: row.boxCode
    result += '<div class="pull-right"><button type="button" id="' + row.id + '-del" class="btn btn-warning btn-sm" onclick="boxLost(\'' + row.purchaseOrderCode + '\',\'' + row.spuName + '\',\'' + row.id + '\',\'' + row.boxCode + '\')">物品缺失</button></div>';
    result += '&emsp;&emsp;<div class="pull-right"><button type="button" id="' + row.id + '-entry" class="btn btn-primary btn-sm" onclick="boxEntryGoodsCollect(\'' + row.purchaseOrderCode + '\',\'' + row.id + '\',\'' + row.boxCode + '\')">全部入库</button></div>';
    return result;
}

//货箱丢失
function boxLost(purchaseOrderCode, spuName, rowId, boxCode) {
    console.log("purchaseOrderCode:" + purchaseOrderCode + ";" + "boxCode:" + boxCode);
    BootstrapDialog.confirm({
        title: '信息提示',
        message: "是否确定当前商品 " + spuName + " 已丢失？",
        btnCancelLabel: '取消', // <-- Default value is 'Cancel',
        btnOKLabel: '确定', // <-- Default value is 'OK',
        callback: function (result) {
            if (result) {
                if (purchaseOrderCode && boxCode) {
                    const opt = {
                        purchaseOrderCode: purchaseOrderCode,
                        boxCode: boxCode,
                        bigProduct: 1,
                        id: rowId,
                        clientId: $("#client-id").val()
                    };
                    $.ajax({
                        type: "POST",
                        url: "/wcs/order/detail/boxLost",
                        contentType: "application/json;charset=UTF-8",
                        data: JSON.stringify(opt),
                        dataType: "json",
                        success: function (data) {
                            if (data.code == 0) {
                                const ids = data.data;
                                if (ids.length > 0) {
                                    for (let i = 0; i < ids.length; i++) {
                                        $('#purchase-detail-table').bootstrapTable('removeByUniqueId', ids[i]);
                                    }
                                }
                            } else {
                                BootstrapDialog.alert(data.msg);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            BootstrapDialog.alert({
                                title: "信息提示！",
                                closable: false,
                                message: XMLHttpRequest.responseJSON.msg
                            });
                        }
                    });
                }
            } else {
            }
        }
    });
}

//平地产商品入库
function boxEntryGoodsCollect(purchaseOrderCode, rowId, boxCode) {
    console.log("boxEntryGoodsCollect:" + purchaseOrderCode + ";" + "boxCode:" + boxCode);
    BootstrapDialog.confirm({
        title: '信息提示',
        message: "是否确定当前所有商品入库地平仓？",
        btnCancelLabel: '取消', // <-- Default value is 'Cancel',
        btnOKLabel: '确定', // <-- Default value is 'OK',
        callback: function (result) {
            if (result) {
                if (purchaseOrderCode && boxCode) {
                    $('#entry-code-info').val(boxCode);
                    $('#box-code-info').val(boxCode);
                    $('#box-code').val(boxCode);
                    $('#ware-box-code').val(boxCode);
                    $('#entry-order-btn').click();
                }
            } else {
            }
        }
    });
}

//货箱详情数据初始化
function insertEntryTable(data, entry) {
    console.log(">>>>>>>>>>>>>");
    let opt = [];
    let volume = 0;
    if (entry.length && entry.width && entry.height) {
        if (entry.numberOfPerBox) {
            volume = parseFloat(entry.length * entry.width * entry.height * entry.numberOfPerBox).toFixed(2);
        } else {
            volume = parseFloat(entry.length * entry.width * entry.height).toFixed(2);
        }
        volume = parseFloat(volume * entry.quantity).toFixed(2);
    }
    //后续做了扩展，只需入库单或者采购单即可，初版是商品对应入库单
    opt.push({
        id: entry.id,
        quantity: entry.quantity,
        shelfLife: entry.shelfLife,
        numberOfPerBox: entry.numberOfPerBox,
        weightOfPerBox: entry.weightOfPerBox,
        spuName: data.spuName,
        temperatureZone: data.temperatureZone,
        temperatureZoneCode: data.temperatureZoneCode,
        batchCode: data.batchCode,
        unit: entry.unit,
        spuId: entry.spuId,
        volume: data.volume,
        produceDate: entry.pickTime,
        warrantyDate: entry.warrantyDate,
        specCode: data.specCode,
        skuCode: data.skuCode,
        entryCode: entry.entryCode,
        supplierCode: entry.supplierCode,
        producerId: entry.producerId,
        purchaseOrderCode: data.purchaseOrderCode,
        purchaseOrderDetailId: data.id,
        weight: entry.weight
    });
    insertRow(opt, 'sort-table', true);
}

//初始化入库箱列表
function initEntryTable(data) {
    $('.outbound-order-cls').addClass("hidden");
    $('.entry-order-cls').removeClass("hidden");
    $('#outbound-nav').removeClass('hidden');
    $('#sort-table').bootstrapTable({
        pagination: false,//不分页
        sortable: false, //不排序
        sidePagination: "server",
        uniqueId: 'id',
        striped: true,
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            let temp = $("#search-condition").serializeJSON();
            /*temp["rows"] = params.limit;                        //页面大小
            temp["page"] = (params.offset / params.limit) + 1;  //页码
            temp["sort"] = params.sort;                         //排序列名
            temp["sortOrder"] = params.order;      */             //排位命令（desc，asc）
            if (data != null) {
                temp["purchaseOrderCode"] = data.purchaseOrderCode;
            }
            return temp;

        },
        onLoadSuccess: function (data) {
            console.log("initEntryTable");
            $('#entry-code-info').focus();
        },
        columns: [{
            field: 'spuName',
            title: '名称'
        }, {
            field: 'temperatureZone',
            title: '温区',
            cellStyle: function (value, row, index) {
                return {
                    css: {
                        // "background-color": "#007AF5",
                        "font-size": '16px;',
                        // "color": "#FFFFFF",
                        "font-weight": "bold"
                    }
                };
            }
        }, {
            field: 'quantity',
            title: '数量'
        }, {
            field: 'unit',
            title: '单位'
        }, {
            field: 'weight',
            title: '采购重量'
        }, /*{
            field: 'actWeight',
            title: '称重重量',
            cellStyle: function (value, row, index) {
                return {
                    css: {
                        // "background-color": "#007AF5",
                        "font-size": '16px;',
                        // "color": "#FFFFFF",
                        "font-weight": "bold"
                    }
                };
            }
        }, */{
            field: 'spuId',
            title: '原料',
            visible: false
        }, {
            field: 'boxCode',
            title: '货箱'
        }, {
            field: 'opt',
            title: '操作',
            align: 'center',
            valign: 'middle',
            formatter: actionFormatter,
        }]
    });
}

//操作栏的格式化
function actionFormatter(value, row, index, field) {
    let result = '';
    // result += '<a href="javascript:;" class="btn btn-xs green" onclick="outOfStock(\'' + row.id + '\')" title="缺货"><span class="glyphicon glyphicon-pencil"></span></a>';
    //未称重，则显示称重按钮，先一直显示
    /*if (!row.weightDone) {
        result += '<button type="button" id="' + row.id + '" class="btn btn-primary" onclick="checkWeight(\'' + row.id + '\')">称重</button>';
    }*/
    const entry = $('#sort-table').bootstrapTable('getData');
    let flag = false;
    //当所有入库单都称重后，才显示称重按钮
    if (entry && entry.length > 1) {
        for (let i = 0; i < entry.length; i++) {
            const item = entry[i];
            if (item && item.actWeight && item.actWeight > 0) {
            } else {
                flag = true;
                break;
            }
        }
    }

    /*if (!flag || !(row.actWeight && row.actWeight > 0)) {
        result += '<div class="pull-left"><button type="button" id="' + row.id + '" class="btn btn-primary btn-sm" onclick="checkWeight(\'' + row.id + '\')">称重</button></div>';
    }
    result += '<div class="pull-right"><button type="button" id="' + row.id + '-del" class="btn btn-primary btn-sm" onclick="cancelEntry(\'' + row.id + '\')">货箱缺失</button></div>';*/
    return result;
}

function checkWeight(id) {
    const orderRow = $('#sort-table').bootstrapTable('getRowByUniqueId', id);
    console.log("采购信息：" + JSON.stringify(orderRow));
    if (orderRow) {
        $('#' + id).hide();
        $('#entry-order-btn').addClass("hidden");
        $('#entry-box').addClass("hidden");
        $('#total-weight').val(orderRow.weight);
        let ops = $("#form-param").serializeJSON();
        ops['upOrDownPolicy']['spuId'] = orderRow.spuId;
        ops['upOrDownPolicy']['skuCode'] = orderRow.skuCode;
        ops['upOrDownPolicy']['specCode'] = orderRow.specCode;
        ops['upOrDownPolicy']['warehousingEntryId'] = id;
        $.ajax({
            type: "POST",
            url: "/wcs/entryWeight",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify(ops),
            dataType: "json",
            success: function (data) {
                if (data.code == 0) {
                } else {
                    $('#' + id).show();
                    $('#entry-order-btn').removeClass("hidden");
                    $('#entry-box').removeClass("hidden");
                    BootstrapDialog.alert(data.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (XMLHttpRequest.responseJSON) {
                    if (XMLHttpRequest.responseJSON.msg) {
                        BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                    } else {
                        BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                    }
                }
            }
        });
    }
}

//取消当前入库单入库
function cancelEntry(id) {
    BootstrapDialog.confirm({
        title: '信息提示',
        message: "是否确定删除当前入库信息？",
        btnCancelLabel: '取消', // <-- Default value is 'Cancel',
        btnOKLabel: '确定', // <-- Default value is 'OK',
        callback: function (result) {
            if (result) {
                const boxCode = $('#box-code').text();
                if (id && boxCode) {
                    const opt = {type: "entry:" + boxCode, clientId: $('#client-id').val(), mapKey: id};
                    console.log("opt=" + JSON.stringify(opt));
                    $.ajax({
                        type: "POST",
                        url: "/wcs/redis/delHashKey",
                        contentType: "application/json;charset=UTF-8",
                        data: JSON.stringify(opt),
                        dataType: "json",
                        success: function (data) {
                            if (data.code == 0) {
                                //删除货箱内入库单数据，以及更新入库明细
                                const row = $('#sort-table').bootstrapTable('getRowByUniqueId', id);
                                const purchaseDetailList = $('#purchase-detail-table').bootstrapTable('getData');
                                if (purchaseDetailList && purchaseDetailList.length > 0 && row) {
                                    for (let i = 0; i < purchaseDetailList.length; i++) {
                                        const purchaseDetail = purchaseDetailList[i];
                                        if (row.batchCode == purchaseDetail.batchCode) {
                                            $('#purchase-detail-table').bootstrapTable('updateByUniqueId', {
                                                id: purchaseDetail.id,
                                                row: {
                                                    purchaseQuantity: purchaseDetail.purchaseQuantity + 1,
                                                    purchaseWeight: purchaseDetail.purchaseWeight + row.weight
                                                }
                                            });
                                            $('#sort-table').bootstrapTable('removeByUniqueId', id);
                                            break;
                                        }
                                    }
                                }
                            } else {
                                BootstrapDialog.alert(data.msg);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            BootstrapDialog.alert({
                                title: "信息提示！",
                                closable: false,
                                message: XMLHttpRequest.responseJSON.msg
                            });
                        }
                    });
                }
            } else {
            }
        }
    });
}

//确认入库
function entryCheck(boxCode, isClear) {
    const prefixOrder = pattern.test(boxCode);
    console.log("prefixOrder=" + prefixOrder);
    if (prefixOrder) {
        $('#box-code').text(boxCode);
        $("#entry-code-info").val("");
        $('#entry-code-info').focus();
        upBox();
        /*const entry = $('#sort-table').bootstrapTable('getData');
        const rows = $('#sort-table').bootstrapTable('getSelections');
        console.log("rows:" + JSON.stringify(rows));
        if (entry && entry.length > 0) {
            for (let i = 0; i < entry.length; i++) {
                const item = entry[i];
                if (item && item.actWeight && item.actWeight > 0) {
                } else {
                    console.log("rows1");
                    BootstrapDialog.show({
                        message: "所有入库单都称重后才能入库",
                        closable: false,
                        onshown: function (dialogRef) {
                            setTimeout(function () {
                                dialogRef.close();
                                clearInput("entry-code-info");
                            }, 3000);
                        },
                        buttons: [{
                            label: '确定',
                            cssClass: 'btn-primary',
                            action: function (dialog) {
                                dialog.close();
                                clearInput("entry-code-info");
                            }
                        }]
                    });
                    return;
                }
            }
            $('#box-code').text(boxCode);
            $("#entry-code-info").val("");
            $('#entry-code-info').focus();
            upBox();
        }*/
        clearInput("entry-code-info");
        /*const entry = $('#sort-table').bootstrapTable('getData');
        let isUp = false;
        if (entry && entry.length > 0) {
            for (let i = 0; i < entry.length; i++) {
                const purchaseDetail = entry[i];
                const flag = $('#' + purchaseDetail.id).is(':hidden');
                console.log("flag=" + flag);
                if (!flag) {
                    isUp = true;
                    break;
                }
            }
            console.log("isUp=" + isUp);
            if (!isUp) {
                //所有入库单都称重后，才入库
                $('#box-code').text(boxCode);
                $("#entry-code-info").val("");
                $('#entry-code-info').focus();
                // upBox();
            } else {
                if (!isClear) {
                    BootstrapDialog.confirm({
                        title: '信息提示',
                        message: "所有入库单都称重后才能入库",
                        btnCancelLabel: '取消', // <-- Default value is 'Cancel',
                        btnOKLabel: '确定', // <-- Default value is 'OK',
                        callback: function (result) {
                            if (result) {
                                clearInput("entry-code-info");
                            } else {
                            }
                        }
                    });
                }
            }
        } else {
            clearInput("entry-code-info");
        }*/
    }
}

/**
 * 从采购单中获取货箱内的物品
 * @param boxCode
 */
function selectBoxInfo(boxCode) {
    const entry = $('#purchase-detail-table').bootstrapTable('getData');
    const arr = new Array();
    if (entry && entry.length > 0) {
        console.log("selectBoxInfoList:" + JSON.stringify(entry.length));
        for (let i = 0; i < entry.length; i++) {
            const temp = entry[i];
            if (temp.boxCode == boxCode) {
                $('#sort-table').bootstrapTable('append', temp);
                arr.push(temp);
            }
        }
        if (arr.length > 0) {
            for (let i = 0; i < arr.length; i++) {
                const temp = arr[i];
                $('#purchase-detail-table').bootstrapTable('removeByUniqueId', temp.id);
            }
        }
    }
}

//入库单查询
function selectByEntryCode(boxCode) {
    // const boxCode = $('#entry-code-info').val();
    const prefixOrder = pattern.test(boxCode);
    console.log("boxCode:" + boxCode);
    if (prefixOrder) {
        const opt = $("#form-param").serializeJSON();
        opt['goodsBox']['boxCode'] = boxCode;
        $.ajax({
            type: "POST",
            url: "/wcs/box/selectEmptyBoxByBoxCode",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify(opt),
            dataType: "json",
            success: function (data) {
                if (data.code == 0) {
                    const goodsBox = data.data;
                    if (goodsBox) {
                        // $('#temp-name').text('(' + goodsBox.temperatureName + ')');
                        // $('#temp-code').text(goodsBox.actTemperatureCode);
                    }
                    initFromEntryOrder(boxCode);
                } else {
                    BootstrapDialog.show({
                        size: BootstrapDialog.SIZE_NORMAL,
                        message: data.msg,
                        closable: false,
                        buttons: [{
                            label: '确定',
                            cssClass: 'btn-primary',
                            action: function (dialog) {
                                dialog.close();
                                $('#ware-box-code').val("");
                                $('#box-code-info').val("");
                                $('#box-code').text("");
                                $("#entry-code-info").val("");
                                $('#entry-code-info').focus();
                                $('#entry-box').removeClass("hidden");
                            }
                        }]
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                BootstrapDialog.alert({
                    title: "信息提示！",
                    closable: false,
                    message: XMLHttpRequest.responseJSON.msg
                });
            }
        });
    } else {
        const stockInCode = $("#entry-code-info").val();
        if (!stockInCode) {
            BootstrapDialog.alert("请扫描或输入入库单");
            $("#entry-code-info").focus();
            return;
        }
        const entryCode = new RegExp("^RKD.*$").test(stockInCode);
        if (entryCode) {
            //采购货箱入库
            let ops = $("#form-param").serializeJSON();
            $.ajax({
                type: "POST",
                url: "/wcs/entry/selectByCode",
                contentType: "application/json;charset=UTF-8",
                data: JSON.stringify(ops),
                dataType: "json",
                success: function (data) {
                    $("#entry-code-info").val("");
                    if (data.code == 0) {
                        const entry = $('#sort-table').bootstrapTable('getData');
                        console.log("入库单返回：" + JSON.stringify(data));
                        console.log("需入库的明细：" + JSON.stringify(entry));
                        //货箱能存放的重量上限
                        const boxWeight = 30;
                        if (data.data) {
                            if (data.data.weight > boxWeight) {
                                BootstrapDialog.show({
                                    message: "重量大于" + boxWeight + "公斤,超重" + parseFloat(data.data.weight - boxWeight).toFixed(2) + "公斤",
                                    closable: false,
                                    buttons: [{
                                        label: '确定',
                                        cssClass: 'btn-primary',
                                        action: function (dialog) {
                                            dialog.close();
                                        }
                                    }]
                                });
                                return;
                            }
                            if (entry.length > 0) {
                                //扫描的入库单总重量
                                let totalWeight = data.data.weight;
                                for (let i = 0; i < entry.length; i++) {
                                    const temp = entry[i];
                                    totalWeight = parseFloat(totalWeight + temp.weight).toFixed(2);
                                }
                                console.log("总重量：" + totalWeight);
                                //不得超过30公斤
                                if (totalWeight > boxWeight) {
                                    BootstrapDialog.show({
                                        message: "重量大于" + boxWeight + "公斤,超重" + parseFloat(totalWeight - boxWeight).toFixed(2) + "公斤",
                                        closable: false,
                                        buttons: [{
                                            label: '确定',
                                            cssClass: 'btn-primary',
                                            action: function (dialog) {
                                                dialog.close();
                                            }
                                        }]
                                    });
                                    return;
                                }
                                //查询入库单是否已扫描
                                for (let i = 0; i < entry.length; i++) {
                                    //入库单已扫描
                                    if (entry[i].id == data.data.id) {
                                        return;
                                    }
                                    if (entry[i].temperatureZoneCode != data.data.temperatureZoneCode) {
                                        BootstrapDialog.show({
                                            message: "同一货箱只能放同一温区物品",
                                            closable: false,
                                            buttons: [{
                                                label: '确定',
                                                cssClass: 'btn-primary',
                                                action: function (dialog) {
                                                    dialog.close();
                                                }
                                            }]
                                        });
                                        return;
                                    }
                                    //每个货箱只能放一箱单位为箱的物品
                                    if (entry[i].unit == '箱') {
                                        BootstrapDialog.show({
                                            message: "每个箱子只能放一箱物品",
                                            closable: false,
                                            onshown: function (dialogRef) {
                                                setTimeout(function () {
                                                    dialogRef.close();
                                                }, 2000);
                                            },
                                            buttons: [{
                                                label: '确定',
                                                cssClass: 'btn-primary',
                                                action: function (dialog) {
                                                    dialog.close();
                                                }
                                            }]
                                        });
                                        return;
                                    }

                                    if (entry[i].actWeight && entry[i].actWeight > 0) {
                                    } else {
                                        BootstrapDialog.show({
                                            message: "有入库单未称重，请称重完成再入库其他入库单",
                                            closable: false,
                                            onshown: function (dialogRef) {
                                                setTimeout(function () {
                                                    dialogRef.close();
                                                    clearInput("entry-code-info");
                                                }, 3000);
                                            },
                                            buttons: [{
                                                label: '确定',
                                                cssClass: 'btn-primary',
                                                action: function (dialog) {
                                                    dialog.close();
                                                    clearInput("entry-code-info");
                                                }
                                            }]
                                        });
                                        return;
                                    }

                                }
                            } else {
                                const tempCode = $('#temp-code').text();
                                if (tempCode != data.data.temperatureZoneCode) {
                                    BootstrapDialog.show({
                                        size: BootstrapDialog.SIZE_NORMAL,
                                        message: "请扫描与货箱相同温区的入库单",
                                        closable: false,
                                        onshown: function (dialogRef) {
                                            setTimeout(function () {
                                                dialogRef.close();
                                            }, 3000);
                                            clearInput("entry-code-info");
                                        },
                                        buttons: [{
                                            label: '确定',
                                            cssClass: 'btn-primary',
                                            action: function (dialog) {
                                                dialog.close();
                                                clearInput("entry-code-info");
                                            }
                                        }]
                                    });
                                    return;
                                }
                            }
                            //行的数据
                            const rows = $('#purchase-detail-table').bootstrapTable('getData');
                            console.log("入库采购明细：" + JSON.stringify(rows));
                            for (let i = 0; i < rows.length; i++) {
                                const purchaseDetail = rows[i];
                                if (data.data.batchCode == purchaseDetail.batchCode) {
                                    if (purchaseDetail.purchaseQuantity - purchaseDetail.entryQuantity <= 0) {
                                        BootstrapDialog.alert("采购数量为0，无法扫描进货箱");
                                        return;
                                    }
                                    //添加到货箱
                                    insertEntryTable(purchaseDetail, data.data);
                                    //采购详情减少一份
                                    let quantity = 0;
                                    if (purchaseDetail.entryQuantity) {
                                        quantity = purchaseDetail.purchaseQuantity - purchaseDetail.entryQuantity - data.data.quantity;
                                    } else {
                                        quantity = purchaseDetail.purchaseQuantity - data.data.quantity;
                                    }
                                    console.log("quantity===" + quantity + ";purchaseDetail.purchaseWeight=" + purchaseDetail.purchaseWeight + ";data.data.weight=" + data.data.weight);
                                    const t = parseFloat(purchaseDetail.purchaseWeight * quantity).toFixed(2);
                                    console.log("mmmm==" + t);
                                    $('#purchase-detail-table').bootstrapTable('updateByUniqueId', {
                                        id: purchaseDetail.id,
                                        replace: false,
                                        row: {
                                            purchaseQuantity: quantity,
                                            purchaseWeight: t
                                        }
                                    });
                                } else {
                                    // BootstrapDialog.alert("原料或批次不匹配");
                                }
                            }
                            $('#entry-code-info').focus();
                        } else {
                            $('#entry-code').val("");
                            BootstrapDialog.show({
                                size: BootstrapDialog.SIZE_NORMAL,
                                message: data.msg,
                                closable: false,
                                onshown: function (dialogRef) {
                                    setTimeout(function () {
                                        dialogRef.close();
                                    }, 3000);
                                    clearInput("entry-order-no");
                                },
                                buttons: [{
                                    label: '确定',
                                    cssClass: 'btn-primary',
                                    action: function (dialog) {
                                        dialog.close();
                                        clearInput("entry-order-no");
                                    }
                                }]
                            });
                        }
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    BootstrapDialog.alert({
                        title: "信息提示！",
                        closable: false,
                        message: XMLHttpRequest.responseJSON.msg
                    });
                }
            });
        } else {
            BootstrapDialog.alert("入库请扫描入库单，上架请扫描货箱编号！");
            $("#entry-code-info").val("");
            $('#entry-code-info').focus();
            return;
        }
    }
}

/**
 * 货物入仓码查询入库单赋值货箱
 */
function initFromEntryOrder(boxCode) {
    let ops = $("#form-param").serializeJSON();
    $.ajax({
        type: "POST",
        url: "/wcs/entry/selectByEntryCodeList",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(ops),
        dataType: "json",
        success: function (data) {
            if (data.data.length > 0) {
                const rows = $('#purchase-detail-table').bootstrapTable('getData');
                console.log("入库采购明细：" + JSON.stringify(rows));
                console.log("入库采购明细size：" + rows.length);
                console.log("入库单明细size：" + data.data.length);
                for (let j = 0; j < data.data.length; j++) {
                    const entry = data.data[j];
                    for (let i = 0; i < rows.length; i++) {
                        const purchaseDetail = rows[i];
                        if (boxCode == entry.boxCode && entry.boxCode == purchaseDetail.boxCode && entry.batchCode == purchaseDetail.batchCode && entry.spuId == purchaseDetail.spuId && entry.skuCode == purchaseDetail.skuCode) {
                            insertEntryTable(purchaseDetail, entry);
                            $('#purchase-detail-table').bootstrapTable('removeByUniqueId', purchaseDetail.id);
                            const rowss = $('#sort-table').bootstrapTable('getData');
                            console.log("扫码入库货箱信息：" + JSON.stringify(rowss));
                        }
                    }
                }
                entryCheck(boxCode, true);
            }
        }
    });

}

//上架
function upBox() {
    const entry = $('#sort-table').bootstrapTable('getData');
    /*const boxCode = $('#box-code').text();
     if (!boxCode && !$('#ware-box-code').val()) {
         BootstrapDialog.alert({
             title: "信息提示！",
             closable: false,
             message: "请扫码输入货箱编号"
         });
         return;
     }

     if (boxCode) {
         $('#ware-box-code').val(boxCode);
         $('#box-code-info').val(boxCode);
     } else {
         $('#box-code-info').val($('#ware-box-code').val());
     }*/
    //采购入库不允许空箱入库，返回空箱出入库处理
    if (entry.length < 1) {
        /*BootstrapDialog.confirm({
            type: BootstrapDialog.TYPE_WARNING,
            title: "信息提示",
            message: "是否空箱入库?",
            btnCancelLabel: '取消',
            btnOKLabel: '确定',
            callback: function (result) {
                // 点击确定按钮时，result为true
                if (result) {
                    entryEmpty(opt)
                }
            }
        });*/
        return;
    } else {
        let opt = $("#form-param").serializeJSON();
        // $('#entry-code-info').attr("disabled", "disabled");
        $('#entry-order-btn').addClass("hidden");
        $('#entry-box').addClass("hidden");
        //转换为详情
        for (let i = 0; i < entry.length; i++) {
            console.log("logs===" + entry[i].id);
            $('#' + entry[i].id).hide();
            $('#' + entry[i].id + "-del").hide();
            entry[i]['weight'] = entry[i]['weight'];
            entry[i]['purchaseWeight'] = entry[i]['purchaseWeight'];
            delete entry[i]['id'];
        }
        opt['list'] = entry;
        opt['tempNum'] = $('#temp-code').text();
        console.log("upBox:" + JSON.stringify(opt));
        $.ajax({
            type: "POST",
            url: "/wcs/purchaseEntry",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify(opt),
            dataType: "json",
            success: function (data) {
                if (data.code == 0) {
                    isEntry();
                } else {
                    BootstrapDialog.show({
                        size: BootstrapDialog.SIZE_NORMAL,
                        message: data.msg,
                        closable: false,
                        buttons: [{
                            label: '确定',
                            cssClass: 'btn-primary',
                            action: function (dialog) {
                                dialog.close();
                                $("#entry-code-info").val("");
                                $('#entry-code-info').focus();
                                $('#entry-box').removeClass("hidden");
                            }
                        }]
                    });
                    for (let i = 0; i < entry.length; i++) {
                        $('#' + entry[i].id).show();
                        $('#' + entry[i].id + "-del").show();
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                BootstrapDialog.alert({
                    title: "信息提示！",
                    closable: false,
                    message: XMLHttpRequest.responseJSON.msg
                });
            }
        });
    }
}

//空箱入库
function entryEmpty(opt) {
    $.ajax({
        type: "POST",
        url: "/wcs/emptyEntry",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
            } else {
                BootstrapDialog.show({
                    size: BootstrapDialog.SIZE_NORMAL,
                    message: data.msg,
                    closable: false,
                    onshown: function (dialogRef) {
                        setTimeout(function () {
                            dialogRef.close();
                        }, 3000);
                    },
                    buttons: [{
                        label: '确定',
                        cssClass: 'btn-primary',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }]
                });
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            BootstrapDialog.alert({
                title: "信息提示！",
                closable: false,
                message: XMLHttpRequest.responseJSON.msg
            });
        }
    });
}